package cn.tedu.tmall.passport.exception;

import cn.tedu.tmall.common.enumerator.ServiceCode;
import cn.tedu.tmall.common.ex.ServiceException;
import cn.tedu.tmall.common.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult handlerServiceException(ServiceException e){
        return JsonResult.fail(e);
    }

    @ExceptionHandler
    public JsonResult handlerBindException(BindException e){
        String message = e.getFieldError().getDefaultMessage();
        return JsonResult.fail(ServiceCode.ERROR_BAD_REQUEST,message);
    }

    @ExceptionHandler
    public JsonResult handlerAccessDeniedException(AccessDeniedException e){
        String message = "操作失败，您当前登陆的账号无此操作权限";
        return JsonResult.fail(ServiceCode.ERROR_FORBIDDEN,message);
    }

    @ExceptionHandler
    public JsonResult handlerThrowable(Throwable e){
        log.error("程序处理过程中出现某种未知的异常："+e);
        String message = "服务器忙，请稍后再试";
        return JsonResult.fail(ServiceCode.ERROR_UNKNOWN,message);
    }
}
